import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_fast_lib/flutter_fast_lib.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';

///基础WebView--基于[WebViewWidget] 增加默认进度条
class FastWebView extends StatefulWidget {
  const FastWebView({
    super.key,
    required this.initialUrl,
    this.initialSettings,
    this.onPermissionRequest,
    this.onWebViewCreated,
    this.gestureRecognizers,
    this.onNavigationRequest,
    this.onProgress,
    this.progressBuilder,
    this.onLoadStart,
    this.showProgress = true,
    this.backgroundColor = Colors.transparent,
    this.clearCache,
    this.clearLocalStorage,
    this.onPageFinished,
    this.onDownloadStartRequest,
    this.onPrintRequest,
    this.onJsAlert,
    this.onJsConfirm,
    this.onJsPrompt,
    this.launcherByBrowser = true,
  });

  //需要加载url-网络地址
  final String initialUrl;
  final InAppWebViewSettings? initialSettings;

  //WebView请求权限
  final Future<PermissionResponse?> Function(InAppWebViewController controller,
      PermissionRequest permissionRequest)? onPermissionRequest;

  //WebViewController 创建回调
  final void Function(InAppWebViewController controller)? onWebViewCreated;
  final Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers;

  //可用于拦截是否加载url
  final Future<NavigationActionPolicy?> Function(
          InAppWebViewController controller, NavigationAction navigationAction)?
      onNavigationRequest;

  //网页加载进度-获取标题头
  final Function(int progress)? onProgress;

  //是否显示顶部进度
  final bool showProgress;

  //背景色
  final Color backgroundColor;

  //进入后清理缓存
  final bool? clearCache;

  //清理本地缓存
  final bool? clearLocalStorage;

  //在是否显示直接通过系统浏览器打开
  final bool launcherByBrowser;

  //加载完成
  final void Function(String url)? onPageFinished;

  // 下载请求
  final void Function(InAppWebViewController controller,
      DownloadStartRequest downloadStartRequest)? onDownloadStartRequest;

  // 打印任务
  final Future<bool?> Function(InAppWebViewController controller, WebUri? url,
      PlatformPrintJobController? printJobController)? onPrintRequest;
  final Future<JsAlertResponse?> Function(
          InAppWebViewController controller, JsAlertRequest jsAlertRequest)?
      onJsAlert;
  final Future<JsConfirmResponse?> Function(
          InAppWebViewController controller, JsConfirmRequest jsConfirmRequest)?
      onJsConfirm;
  final Future<JsPromptResponse?> Function(
          InAppWebViewController controller, JsPromptRequest jsPromptRequest)?
      onJsPrompt;

  //完全自定义进度条
  final Widget Function(
    BuildContext context,
    int progress,
    InAppWebViewController controller,
  )? progressBuilder;

  //页面url变更
  final void Function(InAppWebViewController controller, WebUri? url)?
      onLoadStart;

  @override
  State<FastWebView> createState() => _FastWebViewState();
}

class _FastWebViewState extends State<FastWebView> {
  ///WebViewController
  late final InAppWebViewController _controller;

  ///网页加载进度
  final ValueNotifier<int> _onProgress = ValueNotifier(0);

  late final InAppWebViewSettings? _settings;
  
  /// 是否可以使用WebView
  final ValueNotifier<bool> _useWebView = ValueNotifier(false);

  /// 目标url
  String targetUrl = '';

  // 设置webView配置
  void setWebViewSettings() {
    _settings = InAppWebViewSettings(
      isInspectable: kDebugMode,
      mediaPlaybackRequiresUserGesture: false,
      allowsInlineMediaPlayback: true,
      iframeAllow: "camera; microphone",
      iframeAllowFullscreen: true,
      clearCache: widget.clearCache,
      transparentBackground: true,
      clearSessionCache: widget.clearLocalStorage,
    );
    if (widget.initialSettings != null) {
      Map<String, dynamic>? map = _settings?.toMap();
      map?.addAll(widget.initialSettings?.toMap() ?? {});
      _settings = InAppWebViewSettings.fromMap(map);
    }
    if (true == widget.clearCache || true == widget.clearLocalStorage) {
      InAppWebViewController.clearAllCache();
      _settings?.cacheMode = CacheMode.LOAD_NO_CACHE;
    }
  }

  /// 获取windows版本
  int getWindowsVersion(String productName) {
    int version = 0;
    if (productName.contains('Windows 12')) {
      version = 12;
    } else if (productName.contains('Windows 11')) {
      version = 11;
    } else if (productName.contains('Windows 10')) {
      version = 10;
    } else if (productName.contains('Windows 8.1')) {
      version = 8;
    } else if (productName.contains('Windows 8')) {
      version = 8;
    } else if (productName.contains('Windows 7')) {
      version = 7;
    }
    return version;
  }

  /// 使用系统浏览器打开网页
  void launcherBySystem() async {
    try {
      if (await UrlLauncherPlatform.instance.canLaunch(widget.initialUrl)) {
        bool isSuccess = await UrlLauncherPlatform.instance.launch(
          widget.initialUrl,
          useSafariVC: false,
          useWebView: false,
          enableJavaScript: false,
          enableDomStorage: false,
          universalLinksOnly: false,
          headers: <String, String>{},
        );
        if (!isSuccess) {
          copyToClipboard(widget.initialUrl);
        }
      } else {
        copyToClipboard(widget.initialUrl);
      }
    } catch (e) {
      copyToClipboard(widget.initialUrl);
    }
  }

  @override
  void initState() {
    super.initState();
    if (true == widget.clearLocalStorage || true == widget.clearCache) {
      targetUrl =
          '${widget.initialUrl.contains('?') ? '&' : '?'}millisecondsSinceEpoch=${DateTime.now().millisecondsSinceEpoch}';
    }
    if (FastPlatformUtil.isWindows) {
      DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
      deviceInfo.windowsInfo.then((value) {
        int windowsVersion = getWindowsVersion(value.productName);
        if (windowsVersion >= 11) {
          setWebViewSettings();
          _useWebView.value = true;
        } else {
          if (widget.launcherByBrowser) {
            Future.delayed(
                const Duration(milliseconds: 300), () => launcherBySystem());
          }
        }
      });
    } else {
      setWebViewSettings();
      _useWebView.value = true;
    }
  }

  /// 复制到粘贴板
  void copyToClipboard(String text, {String? successMsg}) async {
    await Clipboard.setData(ClipboardData(text: text));
    FastToastUtil.showSuccess(successMsg ?? '已复制到粘贴板,直接打开浏览器失败!');
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<bool>(
        valueListenable: _useWebView,
        builder: (context, canUse, child) {
          if (canUse) {
            return Column(
              children: [
                ///顶部进度条
                if (widget.showProgress)
                  ValueListenableBuilder<int>(
                    valueListenable: _onProgress,
                    builder: (context, progress, child) {
                      Widget progressWidget = widget.progressBuilder
                              ?.call(context, progress, _controller) ??
                          SizedBox(
                            height: progress != 100 ? 2 : 0,
                            child: LinearProgressIndicator(
                              backgroundColor: Theme.of(context)
                                  .colorScheme
                                  .primary
                                  .withOpacity(0.4),
                              value: progress / 100,
                              color: Theme.of(context).colorScheme.primary,
                            ),
                          );
                      return progressWidget;
                    },
                  ),
                Expanded(
                  child: InAppWebView(
                    initialUrlRequest: URLRequest(
                      url: WebUri('${widget.initialUrl}$targetUrl'),
                      headers: true == widget.clearCache ||
                              true == widget.clearLocalStorage
                          ? {
                              "Cache-Control":
                                  "no-cache, no-store, must-revalidate",
                              "Pragma": "no-cache",
                              "Expires": "0"
                            }
                          : null,
                    ),
                    initialSettings: _settings,
                    onWebViewCreated: (controller) {
                      widget.onWebViewCreated?.call(controller);
                    },
                    onPermissionRequest: widget.onPermissionRequest,
                    shouldOverrideUrlLoading: widget.onNavigationRequest,
                    onProgressChanged: (controller, value) {
                      _onProgress.value = value;
                      widget.onProgress?.call(value);
                    },
                    onLoadStart: widget.onLoadStart,
                    onDownloadStartRequest: widget.onDownloadStartRequest,
                    onPrintRequest: widget.onPrintRequest,
                    onJsAlert: widget.onJsAlert,
                    onJsConfirm: widget.onJsConfirm,
                    onJsPrompt: widget.onJsPrompt,
                    gestureRecognizers: widget.gestureRecognizers ??
                        const <Factory<OneSequenceGestureRecognizer>>{},
                  ),
                ),
              ],
            );
          }
          return Container(
            width: double.infinity,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text('当前系统不支持内置网页展示,请升级windows11以上或点击使用系统内置浏览器打开'),
                if (widget.launcherByBrowser) ...[
                  const SizedBox(height: 16),
                  WebButton(
                    onPressed: () async {
                      launcherBySystem();
                    },
                    text: '系统内置浏览器打开(如果失败请复制到粘贴板)',
                  ),
                ],
                const SizedBox(height: 16),
                WebButton(
                  onPressed: () async {
                    copyToClipboard(
                      widget.initialUrl,
                      successMsg: '已复制到粘贴板!',
                    );
                  },
                  text: '复制到粘贴板',
                ),
              ],
            ),
          );
        });
  }
}

/// 按钮
class WebButton extends StatelessWidget {
  const WebButton({
    super.key,
    required this.onPressed,
    required this.text,
    this.foregroundColor,
    this.backgroundColor,
  });

  final VoidCallback? onPressed;
  final String text;
  final Color? foregroundColor;
  final Color? backgroundColor;

  @override
  Widget build(BuildContext context) {
    var bottomPlus = 0.0;
    if (FastPlatformUtil.isOHOS ||
        FastPlatformUtil.isAndroid ||
        FastPlatformUtil.isWeb ||
        FastPlatformUtil.isWindows) {
      bottomPlus = 4;
    }
    return TextButton(
      onPressed: onPressed,
      style: TextButton.styleFrom(
        foregroundColor: foregroundColor,
        backgroundColor: backgroundColor,
        splashFactory: NoSplash.splashFactory,
        elevation: 0,
        padding: EdgeInsets.only(
          left: 20,
          right: 20,
          top: 16,
          bottom: 16 + bottomPlus,
        ),
      ),
      child: Text(
        text,
        style: TextStyle(
          fontSize: 16,
        ),
      ),
    );
  }
}
